package com.jl.utils;

import com.jl.api.CommonApi;
import com.jl.enums.GameType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class ObjectUtils {

    @Autowired
    private ApplicationContext applicationContext;


    public static <T,R> List<R> convertList(Collection<T> source, Class<R> rClass){
        List<R> collect = source.stream().map(a -> {
            try {
                R r = rClass.newInstance();
                BeanUtils.copyProperties(a, r);
                return r;
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            return null;
        }).collect(Collectors.toList());
        return collect;
    }

    public static String listToStringBySplit(List<String> list,String split){
        if (!CollectionUtils.isEmpty(list)){
            StringBuilder stringBuilder = new StringBuilder();
            for (String str : list) {
                stringBuilder.append(str).append(split);
            }
            String substring = stringBuilder.substring(0, stringBuilder.length() - 1);
            return substring;
        }
        return null;
    }

    public static List<String> distinctList(List<String> list1, List<String> list2){
        List<String> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list1)){list.addAll(list1);}
        if (!CollectionUtils.isEmpty(list2)){list.addAll(list2);}
        List<String> collect = list.parallelStream().distinct().collect(Collectors.toList());
        return collect;
    }

    public CommonApi getTargetService(String gameType){
        Map<String, CommonApi> beansOfType = applicationContext.getBeansOfType(CommonApi.class);
        CommonApi api = null;
        for (Map.Entry<String, CommonApi> map : beansOfType.entrySet()) {
            if (map.getKey().contains(CommonUtils.toLowerCaseFirstOne(GameType.getDesc2ById(gameType)))){
                api = map.getValue();
                break;
            }
        }
        return api;
    }

}
